let Koa = require('koa');

let app = new Koa();


let Router = require('koa-router');

let router = new Router();

let query = require('./db/index');


let bodyparser = require('./middleware/bodyparser');

let timer = require('./middleware/timer');

app.use(timer())

app.use(bodyparser());

app.use(router.routes());

app.use(router.allowedMethods());


//1.自己实现bodyparser中间件

//2.实现一个中间  把每次请求花费的时间，请求方式，请求地址，输出到指定的文件内

//添加地址

router.post('/api/add',async (ctx) => {
    let {username,sex,phone,address,tag,detail} = ctx.request.body;
    if(username&&sex&&phone&&address&&tag&&detail){
        try{
            await query('insert into addresslist (username,sex,phone,address,tag,detail) values (?,?,?,?,?,?)',[username,sex,phone,address,tag,detail]);

            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }

})

//修改地址

router.put('/api/edit',async (ctx) => {
    let {username,sex,phone,address,tag,detail,id} = ctx.request.body;
    if(username&&sex&&phone&&address&&tag&&detail&&id){
        try{
            await query('update addresslist set username=?,sex=?,phone=?,address=?,tag=?,detail=? where id=?',[username,sex,phone,address,tag,detail,id]);

            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }

})

//删除地址

router.delete('/api/del',async (ctx) => {
    let {id} = ctx.request.query;
    if(id){
        try{
            await query('delete from addresslist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//查询地址

router.get('/api/list',async (ctx) => {
    let list = await query('select * from addresslist');
    ctx.body = {
        code:1,
        data:list
    }
})

app.listen(3000,() => {
    console.log("服务器你启动成功")
})